package org.ehe.erp.service.quality.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.erp.domain.quality.ErpQualityItem;
import org.ehe.erp.domain.quality.bo.ErpQualityItemBo;
import org.ehe.erp.domain.quality.vo.ErpQualityItemVo;
import org.ehe.erp.mapper.quality.ErpBomQualityItemMapper;
import org.ehe.erp.mapper.quality.ErpQualityItemMapper;
import org.ehe.erp.service.quality.ErpBomQualityItemService;
import org.ehe.erp.service.quality.ErpQualityItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 质检项目ServiceImpl
 * @author :zhangnn
 * @className :ErpQualityItemServiceImpl
 * @description: TODO
 * @date 2025-09-10 16:34:50
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ErpQualityItemServiceImpl extends ServiceImpl<ErpQualityItemMapper, ErpQualityItem> implements ErpQualityItemService {

    private final ErpQualityItemMapper baseMapper;
    private final ErpBomQualityItemMapper bomQualityItemMapper;

    /**
     * 分页
     * @param bo 查询条件
     * @param pageQuery 分页参数
     * @return
     */
    @Override
    public TableDataInfo<ErpQualityItemVo> queryPageList(ErpQualityItemBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpQualityItem> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(bo.getItemName()),ErpQualityItem::getItemName,bo.getItemName());
        lqw.like(StringUtils.isNotBlank(bo.getItemCode()),ErpQualityItem::getItemCode,bo.getItemCode());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()),ErpQualityItem::getCategory,bo.getCategory());
        IPage<ErpQualityItemVo> erpQualityItemVoIPage = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(erpQualityItemVoIPage);
    }

    @Override
    public List<ErpQualityItemVo> queryList(ErpQualityItemBo bo) {
        LambdaQueryWrapper<ErpQualityItem> lqw = buildQueryWrapper(bo);
        List<ErpQualityItem> list = baseMapper.selectList(lqw);
        return MapstructUtils.convert(list, ErpQualityItemVo.class);
    }

    @Override
    public ErpQualityItemVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public Boolean insertByBo(ErpQualityItemBo bo) {
        // 校验编码唯一性
        if (!checkItemCodeUnique(bo.getItemCode(), null)) {
            throw new RuntimeException("质检项目编码已存在");
        }

        ErpQualityItem add = BeanUtil.toBean(bo, ErpQualityItem.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(ErpQualityItemBo bo) {
        // 校验编码唯一性
        if (!checkItemCodeUnique(bo.getItemCode(), bo.getId())) {
            throw new RuntimeException("质检项目编码已存在");
        }

        ErpQualityItem update = BeanUtil.toBean(bo, ErpQualityItem.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以在这里添加删除前的业务校验逻辑
            // 例如：检查是否被其他模块引用等
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public ErpQualityItem getByItemCode(String itemCode) {
        return baseMapper.selectOne(Wrappers.<ErpQualityItem>lambdaQuery()
            .eq(ErpQualityItem::getItemCode, itemCode));
    }

    @Override
    public Boolean checkItemCodeUnique(String itemCode, Long id) {
        LambdaQueryWrapper<ErpQualityItem> wrapper = Wrappers.<ErpQualityItem>lambdaQuery()
            .eq(ErpQualityItem::getItemCode, itemCode);
        if (ObjectUtil.isNotNull(id)) {
            wrapper.ne(ErpQualityItem::getId, id);
        }
        return baseMapper.selectCount(wrapper) == 0;
    }

    @Override
    public Boolean checkQualityItemUsedByBom(Long qualityItemId) {
        return !bomQualityItemMapper.selectBomsByQualityItemId(qualityItemId).isEmpty();
    }

    @Override
    public List<ErpQualityItemVo> getAvailableQualityItems() {
        LambdaQueryWrapper<ErpQualityItem> wrapper = Wrappers.<ErpQualityItem>lambdaQuery()
            .eq(ErpQualityItem::getStatus, 1)
            .orderByAsc(ErpQualityItem::getSort)
            .orderByAsc(ErpQualityItem::getItemCode);
        List<ErpQualityItemVo> list = baseMapper.selectVoList(wrapper);
        return list;
    }

    @Override
    public List<ErpQualityItemVo> getQualityItemsByCategory(String category) {
        LambdaQueryWrapper<ErpQualityItem> wrapper = Wrappers.<ErpQualityItem>lambdaQuery()
            .eq(ErpQualityItem::getCategory, category)
            .eq(ErpQualityItem::getStatus, 1)
            .orderByAsc(ErpQualityItem::getSort)
            .orderByAsc(ErpQualityItem::getItemCode);
        List<ErpQualityItemVo> list = baseMapper.selectVoList(wrapper);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUpdateStatus(Collection<Long> ids, Integer status) {
        if (status == 0) {
            // 禁用前校验是否被BOM引用
            for (Long id : ids) {
                if (checkQualityItemUsedByBom(id)) {
                    ErpQualityItem item = baseMapper.selectById(id);
                    String itemName = item != null ? item.getItemName() : "ID:" + id;
                    throw new RuntimeException("质检项目[" + itemName + "]已被BOM引用，无法禁用");
                }
            }
        }

        LambdaUpdateWrapper<ErpQualityItem> wrapper = Wrappers.<ErpQualityItem>lambdaUpdate()
            .in(ErpQualityItem::getId, ids)
            .set(ErpQualityItem::getStatus, status);
        return baseMapper.update(null, wrapper) > 0;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<ErpQualityItem> buildQueryWrapper(ErpQualityItemBo bo) {
        LambdaQueryWrapper<ErpQualityItem> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getItemCode()), ErpQualityItem::getItemCode, bo.getItemCode());
        lqw.like(StringUtils.isNotBlank(bo.getItemName()), ErpQualityItem::getItemName, bo.getItemName());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), ErpQualityItem::getCategory, bo.getCategory());
        lqw.eq(ObjectUtil.isNotNull(bo.getIsRequired()), ErpQualityItem::getIsRequired, bo.getIsRequired());
        lqw.eq(ObjectUtil.isNotNull(bo.getStatus()), ErpQualityItem::getStatus, bo.getStatus());
        lqw.orderByAsc(ErpQualityItem::getSort);
        return lqw;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpQualityItem entity) {
        // 可以在这里添加保存前的数据校验逻辑
        if (ObjectUtil.isNull(entity.getSort())) {
            entity.setSort(0);
        }
        if (ObjectUtil.isNull(entity.getIsRequired())) {
            entity.setIsRequired(0);
        }
        if (ObjectUtil.isNull(entity.getStatus())) {
            entity.setStatus(1);
        }
    }
}
